﻿using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Specialized;

namespace StockTradier.Trading
{
    public partial class CreateOrder : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int AccountNumber = 57368375;
            string Token = "mMBoORCH9TnSJlHcOd7fwAaEYDub";

            if (IsPostBack)
            {
                try
                {
                    RestClient client = new RestClient("https://api.tradier.com");
                    var request = new RestRequest(string.Format("/v1/accounts/{0}/orders", AccountNumber), Method.POST);
                    request.AddHeader("Content-type", "application/json");
                    request.AddHeader("Authorization", "{access " + Token + "}");

                    AppendRequest(Request.Form, request);

                    var result = (client.Execute(request).Content);
                    var json = JObject.Parse(result);
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }

        private void AppendRequest(NameValueCollection nameCollection, RestRequest request)
        {
            if (!string.IsNullOrEmpty(nameCollection["class"]))
            {
                request.AddParameter("class", nameCollection["class"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["symbol"]))
            {
                request.AddParameter("symbol", nameCollection["symbol"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["duration"]))
            {
                request.AddParameter("duration", nameCollection["duration"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["side"]))
            {
                request.AddParameter("side", nameCollection["side"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["quantity"]))
            {
                request.AddParameter("quantity", nameCollection["quantity"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["type"]))
            {
                request.AddParameter("type", nameCollection["type"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["price"]))
            {
                request.AddParameter("price", nameCollection["price"]);
            }
            if (!string.IsNullOrEmpty(nameCollection["stop"]))
            {
                request.AddParameter("stop", nameCollection["stop"]);
            }
        }
    }
}